const mysql = require('mysql2/promise');
const dbConfig = require('../config/db.config');

class DatabaseInitializer {
  constructor() {
    this.connection = null;
  }

  async connect() {
    try {
      this.connection = await mysql.createConnection({
        host: dbConfig.host,
        user: dbConfig.user,
        password: dbConfig.password,
        port: dbConfig.port
      });
      console.log('已连接到MySQL数据库');
    } catch (error) {
      console.error('连接MySQL数据库时出错:', error);
      throw error;
    }
  }

  async createDatabase() {
    try {
      await this.connection.execute(`CREATE DATABASE IF NOT EXISTS \`${dbConfig.database}\``);
      console.log(`数据库 ${dbConfig.database} 已创建或已存在`);
    } catch (error) {
      console.error('创建数据库时出错:', error);
      throw error;
    }
  }

  async initializeTables() {
    try {
      // 使用数据库
      await this.connection.execute(`USE \`${dbConfig.database}\``);
      
      // 创建无人机表
      await this.connection.execute(`
        CREATE TABLE IF NOT EXISTS drones (
          id VARCHAR(50) PRIMARY KEY,
          name VARCHAR(100),
          status ENUM('active', 'inactive') DEFAULT 'active',
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
      `);
      
      // 创建流媒体表
      await this.connection.execute(`
        CREATE TABLE IF NOT EXISTS streams (
          id INT AUTO_INCREMENT PRIMARY KEY,
          drone_id VARCHAR(50),
          stream_name VARCHAR(100),
          rtmp_url VARCHAR(255),
          source_url VARCHAR(500) COMMENT '源地址(RTMP/RTSP)',
          source_type ENUM('RTMP', 'RTSP', 'OTHER') COMMENT '源类型',
          status ENUM('active', 'inactive') DEFAULT 'active',
          start_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          end_time TIMESTAMP NULL,
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          FOREIGN KEY (drone_id) REFERENCES drones(id) ON DELETE CASCADE,
          INDEX idx_drone_id (drone_id),
          INDEX idx_status (status),
          INDEX idx_source_type (source_type)
        )
      `);
      
      // 创建流转发记录表
      await this.connection.execute(`
        CREATE TABLE IF NOT EXISTS stream_forwards (
          id INT AUTO_INCREMENT PRIMARY KEY,
          stream_id INT,
          target_rtmp_url VARCHAR(255),
          status ENUM('active', 'inactive') DEFAULT 'active',
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          FOREIGN KEY (stream_id) REFERENCES streams(id) ON DELETE CASCADE
        )
      `);
      
      console.log('数据库表初始化成功');
    } catch (error) {
      console.error('初始化表时出错:', error);
      throw error;
    }
  }

  async close() {
    if (this.connection) {
      await this.connection.end();
      console.log('数据库连接已关闭');
    }
  }

  async init() {
    // 如果数据库已经存在且表结构已经创建，则不需要初始化
    // 可以通过配置文件中的 initializeDatabase 选项来控制
    if (dbConfig.initializeDatabase === false) {
      console.log('根据配置跳过数据库初始化');
      return;
    }
    
    try {
      await this.connect();
      await this.createDatabase();
      await this.initializeTables();
      await this.close();
      console.log('数据库初始化完成');
    } catch (error) {
      console.error('数据库初始化失败:', error);
      await this.close();
      throw error;
    }
  }
}

module.exports = DatabaseInitializer;